
package com.inputabc.qrcoderv1.util;

import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;


/**
 * @author 谢学勤
 * @author gaoweiyi
 * @version 1.1
 * 二维码工具类
 * @date 2021-9-2
 * @since 2017-4-12 下午3:19:09
 */
public class QRCodeUtil {

    private static String CHARSET = "utf-8";
    private static String FORMAT_NAME = "PNG";
    private static int COLOR_FG = 0xFF000000;
    private static int COLOR_BG = 0xFFFFFFFF;
    // 二维码尺寸
    private static int QRCODE_SIZE = 150;
    // LOGO压缩后的宽度
    private static int WIDTH = 150;
    // LOGO压缩后的高度
    private static int HEIGHT = 150;

    public static void setWidth(int width) {
        WIDTH = width;
    }

    public static void setHeight(int height) {
        HEIGHT = height;
    }

    public static void setQrcodeSize(int size) {
        QRCODE_SIZE = size;
    }

    public static void setFormatName(String formatName) {
        FORMAT_NAME = formatName;
    }

    public static void setCharset(String charset) {
        CHARSET = charset;
    }

    public static void setColorBg(int color) {
        COLOR_BG = color;
    }

    public static void setColorFg(int color) {
        COLOR_FG = color;
    }

    public static int getQRCodeSize() {
        return QRCODE_SIZE;
    }

    public static BufferedImage createImage(String content) throws Exception {
        if (content.length() > 1000) {
            throw new MyException("内容不能超过1000字");
        }
        Map<EncodeHintType, Object> hints = new HashMap<>(16);
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 0);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
                BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? COLOR_FG
                        : COLOR_BG);
            }
        }
        return image;
    }

    /**
     * 插入LOGO
     * <p>
     * 若logo图片比二维码图片大，就需要压缩
     * </p>
     *
     * @param source       二维码图片
     * @param imgPath      LOGO图片地址
     * @param needCompress 是否压缩LOGO
     * @throws Exception
     */
    public static void insertImage(BufferedImage source, String imgPath,
                                   boolean needCompress) throws Exception {
        if (imgPath == null || imgPath.trim().equals("")) {
            return;
        }
        File file = new File(imgPath);
        if (!file.exists()) {
            throw new MyException("Logo图片不存在！");
        }
        Image src = ImageIO.read(new File(imgPath));
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        if (needCompress) {
            width = WIDTH;
            height = HEIGHT;
            Image image = src.getScaledInstance(width, height,
                    Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            // 绘制缩小后的图
            g.drawImage(image, 0, 0, null);
            g.dispose();
            src = image;
        }
        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        int x = (QRCODE_SIZE - width) / 2;
        int y = (QRCODE_SIZE - height) / 2;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, height, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

    /**
     * 生成二维码(内嵌LOGO)
     *
     * @param content      内容
     * @param imgPath      LOGO地址
     * @param destPath     存放目录
     * @param needCompress 是否压缩LOGO
     * @throws Exception
     */
    public static String encode(String content, String imgPath, String destPath,
                                boolean needCompress, String name) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content);
        insertImage(image, imgPath, needCompress);
        String file = "";
        if (name != null && !name.trim().equals("")) {
            file = name + "." + FORMAT_NAME;
        } else {
            while (true) {
                String time = new SimpleDateFormat("yyyy-MM-dd--HH-mm-ss--").format(new Date());
                file = time+UUID.randomUUID().toString().replace("-", "").substring(10) + "." + FORMAT_NAME;
                if (new File(destPath, file).exists() == false) {
                    break;
                }
            }
        }
        File targetFile = new File(destPath, file);
        ImageIO.write(image, FORMAT_NAME, targetFile);
        return targetFile.getAbsolutePath();
    }


    /**
     * 生成二维码(内嵌LOGO)
     *
     * @param content  内容
     * @param imgPath  LOGO地址
     * @param destPath 存储地址
     * @throws Exception
     */
    public static void encode(String content, String imgPath, String destPath, String name)
            throws Exception {
        QRCodeUtil.encode(content, imgPath, destPath, false, name);
    }

    /**
     * 生成二维码
     *
     * @param content  内容
     * @param destPath 存储地址
     * @throws Exception
     */
    public static void encode(String content, String destPath, String name) throws Exception {
        QRCodeUtil.encode(content, null, destPath, false, name);
    }


    /**
     * 生成二维码(内嵌LOGO)
     *
     * @param content 内容
     * @param imgPath LOGO地址
     * @param output  输出流
     * @throws Exception
     */
    public static void encode(String content, String imgPath, boolean needCompress,
                              OutputStream output) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content);
        insertImage(image, imgPath, needCompress);
        ImageIO.write(image, FORMAT_NAME, output);
    }

    /**
     * 生成二维码(内嵌LOGO)
     *
     * @param content
     * @param imgPath
     * @param output
     * @throws Exception
     */
    public static void encode(String content, String imgPath, OutputStream output) throws Exception {
        encode(content, imgPath, false, output);
    }

    /**
     * 生成二维码
     *
     * @param content 内容
     * @param output  输出流
     * @throws Exception
     */
    public static void encode(String content, OutputStream output)
            throws Exception {
        QRCodeUtil.encode(content, null, false, output);
    }

    /**
     * 解析二维码
     *
     * @param file 二维码图片
     * @return
     * @throws Exception
     */
    public static String decode(File file) throws Exception {
        BufferedImage image;
        image = ImageIO.read(file);
        if (image == null) {
            return null;
        }
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(
                image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result;
        Map<DecodeHintType, Object> hints = new HashMap<>(16);
        hints.put(DecodeHintType.ALLOWED_LENGTHS, 2000);
        hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
        hints.put(DecodeHintType.TRY_HARDER, true);
        result = new MultiFormatReader().decode(bitmap, hints);
        String resultStr = result.getText();
        return resultStr;
    }

    /**
     * 解析二维码
     *
     * @param path 二维码图片地址
     * @return
     * @throws Exception
     */
    public static String decode(String path) throws Exception {
        return QRCodeUtil.decode(new File(path));
    }

  /*  public static void main(String[] args) throws Exception {
        QRCodeUtil.setQrcodeSize(500);
        QRCodeUtil.setFormatName("png");
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("d:/other/XMLUtils.java"), "utf-8"));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append(System.lineSeparator());
        }
        br.close();
        encode(sb.toString().substring(0,999), "d:/other/close.png","d:/", "logo");
        String decode = decode("d:/logo.png");
       System.out.println(decode);
    }*/
}